<template>
    <v-container fluid>
        <v-container fluid>
            <h4 class="mb-3">员工管理</h4>

            <v-row align="center">
                <v-col :md="2" :sm="6">
                    <AutocompleteOrg v-model="queryOrg" item-key="org_code"></AutocompleteOrg>
                </v-col>
                <v-col :md="2" :sm="6">
                    <AutocompleteUser label="姓名" v-model="queryName" item-text="name"></AutocompleteUser>
                </v-col>
                 <v-col :md="2" :sm="6">
                    <AutocompleteUser label="手机号" v-model="queryMobile" item-text="mobile"></AutocompleteUser>
                </v-col>
                <v-col :md="2" :sm="6">
                    <v-text-field label="邀约人" v-model="queryParent" ></v-text-field>
                </v-col>
                <v-col :md="2" :sm="6">
                    <v-select :items="kycItem"  clearable v-model="queryKyc" label="认证"> </v-select>
                </v-col>

                <v-col :md="4" :sm="6">
                    <v-btn
                        dark
                        class="mb-2 mr-2"
                        @click="query()"
                    >查询
                    </v-btn>

                    <v-btn
                        dark
                        class="mb-2 mr-2"
                        @click="reset()"
                    >重置
                    </v-btn>

                     <v-btn
                        color="primary"
                        dark
                        class="mb-2 mr-2"
                        v-if="is_supper || is_manager"
                        @click="create()"
                    >新增
                    </v-btn>

                    <v-menu bottom offset-y v-if="is_supper  || is_manager">
                        <template v-slot:activator="{ on, attrs }">
                            <v-btn
                                color="primary"
                                dark
                                v-bind="attrs"
                                v-on="on"
                                class="mb-2 mr-2"
                            >
                            资产下拨
                            </v-btn>
                        </template>
                        <v-list>
                            <v-list-item v-if="is_supper || is_manager"  @click="transferDialog = true" >
                                资金余额下拨
                            </v-list-item>
                            <v-list-item  v-if="is_supper || is_manager"  @click="transferTicketDialog = true" >
                                金币下拨
                            </v-list-item>
                        </v-list>
                    </v-menu>
                </v-col>
            </v-row>
        </v-container>

        <v-data-table
            item-key="id"
            :headers="headers"
            :items="items"
            class="elevation-1"
            no-data-text="没有数据..."
            :page.sync="pageNo"
            :items-per-page="pageSize"
            hide-default-footer
        >
            <template v-slot:[`item.id`]="{ item }">
                <router-link :to="`/user/${item.id}`" class="text-decoration-none">{{item.id}}</router-link>
            </template>

           <template v-slot:[`item.actions`]="{ item, index }">
                <v-btn v-if="is_supper || is_manager" small depressed @click="edit(item, index)">编辑</v-btn>
                <v-btn  small depressed :to="`/user/${item.id}`">详情</v-btn>
            </template>

            <template v-slot:[`item.kyc_name`]="{ item }">
               <span  class="red--text" v-if="item.kyc == 1">
                    {{item.kyc_name}}
               </span>
               <span v-else>
                    {{item.kyc_name}}
               </span>
            </template>

            <template v-slot:[`item.parent`]="{ item }">
                <div v-if="item.parent">{{item.parent.name}}<br>{{item.parent.mobile}}</div>
                <div v-else>--</div>
            </template>

        </v-data-table>

        <v-row v-if="items.length > 0 && totalPage >= 1" class="mt-2">
            <v-col cols="12">
                <v-pagination
                    v-model="pageNo"
                    :length="totalPage"
                    :total-visible="7"
                    @input="onPageChange"
                ></v-pagination>
            </v-col>
        </v-row>

        <v-dialog
            v-model="dialog"
            persistent
            max-width="400px"
        >
            <v-form ref="form">
                <v-card>
                    <v-card-title>
                        <span class="text-h5" v-if="selectedItem && selectedItem.id" >编辑员工</span>
                        <span class="text-h5" v-else >新增员工</span>
                    </v-card-title>
                    <v-card-text>
                    <v-row>
                        <v-col cols="12">
                            <AutocompleteOrg :rules="[rules.required]" v-model="selectedItem.org"></AutocompleteOrg>
                        </v-col>
                        <v-col cols="6" >
                            <v-text-field
                                label="姓名"
                                :rules="[rules.required, rules.size]"
                                v-model="selectedItem.name"
                            ></v-text-field>
                        </v-col>
                        <v-col cols="6" >
                            <v-text-field
                                label="电话"
                                v-model="selectedItem.mobile"
                                 :rules="[rules.required, rules.size]"
                            ></v-text-field>
                        </v-col>
                        <v-col cols="4" >
                            <v-select :items="genderItem"  v-model="selectedItem.gender" :rules="[rules.required]" label="性别"> </v-select>
                        </v-col>
                        <v-col cols="4" >
                             <v-select :items="roleItem"  v-model="selectedItem.role"  :rules="[rules.required]" label="职位"> </v-select>
                        </v-col>
                        <v-col cols="4" >
                            <v-select :items="statusItem"  v-model="selectedItem.status"  :rules="[rules.required]" label="状态"> </v-select>
                        </v-col>
                    </v-row>

                    </v-card-text>
                    <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn  depressed   @click="dialog = false" :disabled="saving">
                        关闭
                    </v-btn>
                    <v-btn   depressed  color="primary" dark  @click="save()" :loading="saving">
                        确定
                    </v-btn>
                    </v-card-actions>
                </v-card>
            </v-form>
        </v-dialog>


        <v-dialog
            v-model="transferDialog"
            persistent
            max-width="500px"
        >
            <v-form ref="transferForm">
                <v-card>
                    <v-card-title>
                        <span class="text-h5">分配用户[{{user.name}}]资金给: </span>
                    </v-card-title>
                    <v-card-text>

                    <v-row>
                        <v-col cols="12">
                            <AutocompleteUser :rules="[rules.required]" v-model="transferToUser"></AutocompleteUser>
                        </v-col>
                         <v-col cols="12">
                            <v-text-field
                                label="金额"
                                type="number"
                                v-model="transferAmount"
                                :rules="[rules.required, rules.positive]"
                            ></v-text-field>
                        </v-col>
                    </v-row>

                    </v-card-text>
                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn  depressed   @click="transferDialog = false" :disabled="transfering">
                            关闭
                        </v-btn>
                        <v-btn   depressed  color="primary" dark :loading="transfering" @click="transfer">
                            确定
                        </v-btn>
                    </v-card-actions>
                </v-card>
            </v-form>
        </v-dialog>

        <v-dialog
            v-model="transferTicketDialog"
            persistent
            max-width="500px"
        >
            <v-form ref="transferTicketForm">
                <v-card>
                    <v-card-title>
                        <span class="text-h5">分配用户[{{user.name}}]次数给: </span>
                    </v-card-title>
                    <v-card-text>

                    <v-row>
                        <v-col cols="12">
                            <AutocompleteUser :rules="[rules.required]" v-model="transferToUser"></AutocompleteUser>
                        </v-col>
                         <v-col cols="12">
                            <v-text-field
                                label="次数"
                                type="number"
                                v-model="transferTicketAmount"
                                :rules="[rules.required, rules.positive]"
                            ></v-text-field>
                        </v-col>
                    </v-row>

                    </v-card-text>
                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn  depressed   @click="transferTicketDialog = false" :disabled="transfering">
                            关闭
                        </v-btn>
                        <v-btn   depressed  color="primary" dark :loading="transfering" @click="transferTicket">
                            确定
                        </v-btn>
                    </v-card-actions>
                </v-card>
            </v-form>
        </v-dialog>
    </v-container>
</template>

<script>
    import axios from "axios";
    import AutocompleteOrg from "../../widgets/AutocompleteOrg.vue";
    import AutocompleteUser from "../../widgets/AutocompleteUser.vue";
    import { mapGetters } from 'vuex';

    export default {
        data: () => ({
            headers: [
                { text: '序号', value: 'id' },
                { text: '组织名称', value: 'org.name' },
                { text: '姓名', value: 'name' },
                { text: '手机号', value: 'mobile' },
                { text: '邀约人', value: 'parent' },
                { text: '账户余额', value: 'money' },
                { text: '金币余额', value: 'ticket' },
                { text: '岗位', value: 'role' },
                { text: '性别', value: 'gender_name' },
                { text: '状态', value: 'status_name' },
                { text: '认证', value: 'kyc_name' },
                { text: '加入时间', value: 'created_at' },
                { text: '操作', value: 'actions', sortable: false },
            ],
            items: [],
            pageNo: 1,
            pageSize: 20,
            totalPage: 0,
            rules: {
                required: value => !!value || '必填',
                size: v => (v && v.length >= 2) || '最少2个字符',
                positive: v => (v &&  /^([1-9][0-9]*)$/.test(v) ) || '必须大于0的正整数',
            },
            queryName: null,
            queryMobile: null,
            queryOrg: null,
            queryParent: null,
            queryKyc: null,
            dialog: false,
            statusItem: [
                { value: 1, text: '正常' },
                { value: 2, text: '休假' },
                { value: 3, text: '离职' },
            ],
            genderItem: [
                { value: 1, text: '男' },
                { value: 2, text: '女' },
            ],
            roleItem: [
                { value: '经理', text: '经理' },
                { value: '电销', text: '电销' },
                { value: '面销', text: '面销' },
                { value: '财务', text: '财务' },
                { value: '前台', text: '前台' },
                { value: '渠道', text: '渠道' },
            ],
            kycItem: [
                { value: -1, text: '认证失败' },
                { value: '00', text: '未认证' },
                { value: 1, text: '申请中' },
                { value: 2, text: '认证成功' },
            ],
            saving: false,
            selectedItem: {},
            transferDialog: false,
            transferToUser: null,
            transferAmount: '',
            transfering: false,

            transferTicketDialog: false,
            transferTicketAmount: '',
        }),


        components: {
            AutocompleteOrg: AutocompleteOrg,
            AutocompleteUser: AutocompleteUser,
        },

        computed: {
            ...mapGetters([
                'is_supper',
                'is_manager',
                'user'
            ]),
        },

        created() {
            this.loadList();
        },

        methods: {
            loadList() {
                this.loading = true;
                const that = this;

                const params = Object.entries({
                    pageSize: this.pageSize,
                    page: this.pageNo,
                    name: this.queryName ? this.queryName.name : '',
                    mobile: this.queryMobile ? this.queryMobile.mobile : '',
                    parent: this.queryParent ? this.queryParent : '',
                    org_code: this.queryOrg ? this.queryOrg.org_code : '',
                    kyc: this.queryKyc ? this.queryKyc : null,
                }).reduce((a,[k,v]) => (v ? (a[k]=v, a) : a), {});

                axios.get(`/user`, {
                    params: params
                }).then((response) => {
                    if(response.data.data.length >= 0) {
                        this.items = response.data.data;
                        this.totalPage = response.data.last_page;
                    }
                })
                .catch(function () {})
                .then(function () {
                    that.loading = false;
                });
            },

            onPageChange() {
                this.loadList();
            },

            query() {
                this.pageNo = 1;
                this.loadList();
            },

            reset() {
                this.queryName = null;
                this.queryMobile = null;
                this.queryParent = null;
                this.queryOrg = null;
                this.queryKyc = null;
                this.pageNo = 1;
                this.loadList();
            },


            edit(item, index) {
                this.dialog = true;
                this.selectedItem = JSON.parse(JSON.stringify(item));
            },

            create() {
                this.dialog = true;
                this.selectedItem = {};
            },


            transfer() {
                if (!this.$refs.transferForm.validate()) {
                  return;
                }

                const that = this;
                that.transfering = true;
                axios.post(`/user/money/transfer`, { amount: this.transferAmount, toUser: this.transferToUser.id}).then((response) => {
                    if (response.data.code == 0) {
                        that.loadList();
                        that.transferDialog = false;
                        that.transferAmount = '';
                    }

                    this.$toast.open({
                        message: response.data.msg,
                        type: response.data.code == 0 ? 'success' : 'error',
                        position: 'top-right',
                    });
                }).catch(function () {})
                .then(function () {
                    that.transfering = false;
                });
            },


            transferTicket() {
                if (!this.$refs.transferTicketForm.validate()) {
                  return;
                }

                const that = this;
                that.transfering = true;
                axios.post(`/user/ticket/transfer`, { amount: this.transferTicketAmount, toUser: this.transferToUser.id}).then((response) => {
                    if (response.data.code == 0) {
                        that.loadList();
                        that.transferTicketDialog = false;
                        that.transferTicketAmount = '';
                    }

                    this.$toast.open({
                        message: response.data.msg,
                        type: response.data.code == 0 ? 'success' : 'error',
                        position: 'top-right',
                    });
                }).catch(function () {})
                .then(function () {
                    that.transfering = false;
                });
            },

            save() {
                if (!this.$refs.form.validate()) {
                  return;
                }

                let url = '/user';
                if (this.selectedItem && this.selectedItem.id) {
                    url = `/user/${this.selectedItem.id}`;
                }
                const that = this;
                that.saving = true;
                axios.post(url, { ...this.selectedItem}).then((response) => {
                    if (response.data.code == 0) {
                        this.loadList();
                        that.dialog = false;
                    }

                    this.$toast.open({
                        message: response.data.msg,
                        type: response.data.code == 0 ? 'success' : 'error',
                        position: 'top-right',
                    });
                }).catch(function () {})
                .then(function () {

                    that.saving = false;
                });
            }
        }
    }
</script>
